var express = require('express');
var router = express.Router();
/*var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/blog";*/
var MarkdownIt = require('markdown-it'),
    md = new MarkdownIt();


var mongodbModel = require('./mongodbModel');
var articleList = new mongodbModel('blog', 'article');
var article = new mongodbModel('blog', 'articles');
var mySelf = new mongodbModel('blog', 'Myself');
var tag = new mongodbModel('blog', 'tag');
var link = new mongodbModel('blog', 'link');


articleList.init();
article.init();
mySelf.init();
tag.init();
link.init()
/* GET home page. */
router.get('/', function (req, res, next) {
    Promise.all([
        articleList.find(),
        tag.find(),
        link.find()
    ]).then(([result, tag, link]) => {
            res.render('page/home', {article_list: result, hot_list: result.slice(0, 7), tag: tag, link: link});
        }
    ).catch()
});
router.get('/about', function (req, res, next) {
    mySelf.find().then(result => {
        res.render('page/about', {about: md.render(result[0].content)});
    }).catch()
});
router.get('/articles/list', function (req, res, next) {
    Promise.all([
        articleList.find(),
        tag.find(),
        link.find()
    ]).then(([result, tag, link]) => {
            res.render('page/articlelist', {article_list: result, hot_list: result, tag: tag, link: link});
        }
    ).catch()
});

router.get('/article/:Id', function (req, res, next) {
    Promise.all([
        articleList.find({article_id: req.params.Id - 0}),
        article.find({article_id: req.params.Id - 0})
    ]).then(
        ([basic, content]) => {
            var a=(basic[0].view_count+1)
            articleList.update({article_id: req.params.Id - 0}, {$set: {view_count:a}})
            res.render('page/article', {basic: basic[0], content: md.render(content[0].content)});
        }
    ).catch(() => {
            res.redirect('/404')
        }
    )
});
router.get('/404', function (req, res, next) {
    res.render('page/404')
});

module.exports = router;
